#! /usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime


from flask import Blueprint
from flask import request
from flask_login import login_required
import flask_excel as excel

from app.models import Client, Loan


bp = Blueprint("download", __name__)


@bp.route('/preloan.xlsx', methods=['GET'])
# @login_required
def preloan_xlsx():
    mobile = request.args.get('mobile', "")
    cname = request.args.get('cname', "")
    entry = request.args.get("entry", 0, int)
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    status = request.args.get("status", -1, int)

    query = Loan.query.join(Client, Loan.client_id == Client.id)
    if mobile:
        query = query.filter(Client.mobile.like("%" + mobile + "%"))
    if cname:
        query = query.filter(Client.username.like("%" + cname + "%"))
    if start_time:
        query = query.filter(Loan.start_time >= start_time)
    if end_time:
        my_end_time = end_time + " 23:59:59"
        query = query.filter(Loan.start_time < my_end_time)
    if status >= 1:
        query = query.filter(Loan.status == status)
    if entry:
        query = query.filter(Loan.entry == entry)

    data = [[u'序号', u'手机号码', u'客户姓名', u'贷款金额',
             u"手续费", u"偿还金额", u"开始日期", u"结束日期", u"iphone型号",
             u"入口", u"贷款备注", u"借款状态", u"结束时间", u"是否结束"]]
    loans = query.order_by(
        Loan.create_time.desc()).order_by(Loan.id.desc()).all()

    for index, loan in enumerate(loans):
        loan_closed_time = loan.closed_time if loan.closed_time else ""
        loan_start_time = loan.start_time.strftime("%Y-%m-%d")
        loan_end_time = loan.end_time.strftime("%Y-%m-%d")

        data.append([
            index+1, loan.client.mobile, loan.client.username, loan.money,
            loan.commission, loan.repayment, loan_start_time, loan_end_time, loan.iphone,
            loan.entry_words, loan.comment, loan.status_words,
            loan_closed_time, loan.end_words
        ])
    return excel.make_response_from_array(data, "xlsx")


@bp.route('/froce_loan.xlsx', methods=['GET'])
# @login_required
def force_loan_xlsx():
    today = datetime.now().strftime("%Y-%m-%d")
    mobile = request.args.get('mobile', "")
    cname = request.args.get('cname', "")
    entry = request.args.get("entry", 0, int)
    start_time = request.args.get('start_time', today)
    end_time = request.args.get('end_time', today)

    end = (0, 2)  # 贷款中，逾期为还
    query = Loan.query.join(Client, Loan.client_id == Client.id)
    query = query.filter(Loan.end.in_(end))

    if mobile:
        query = query.filter(Client.mobile.like("%" + mobile + "%"))
    if cname:
        query = query.filter(Client.username.like("%" + cname + "%"))
    if start_time:
        query = query.filter(Loan.end_time >= start_time)
    if end_time:
        my_end_time = end_time + " 23:59:59"
        query = query.filter(Loan.end_time < my_end_time)
    if entry:
        query = query.filter(Loan.entry == entry)

    loans = query.order_by(Loan.id.desc()).all()
    data = [[u'序号', u'手机号码', u'客户姓名', u'贷款金额',
             u"手续费", u"偿还金额", u"开始日期", u"结束日期", u"iphone型号",
             u"入口", u"贷款备注", u"借款状态", u"是否结束"]]

    for index, loan in enumerate(loans):
        loan_start_time = loan.start_time.strftime("%Y-%m-%d")
        loan_end_time = loan.end_time.strftime("%Y-%m-%d")

        data.append([
            index+1, loan.client.mobile, loan.client.username, loan.money,
            loan.commission, loan.repayment, loan_start_time, loan_end_time, loan.iphone,
            loan.entry_words, loan.comment, loan.status_words, loan.end_words
        ])
    return excel.make_response_from_array(data, "xlsx")


@bp.route("/loaned.xlsx", methods=["GET"])
# @login_required
def loaned_xlsx():
    mobile = request.args.get('mobile', "")
    cname = request.args.get('cname', "")
    entry = request.args.get("entry", 0, int)
    l_end = request.args.get("l_end", 1, int)
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')

    query = Loan.query.join(Client, Loan.client_id == Client.id)

    if mobile:
        query = query.filter(Client.mobile.like("%" + mobile + "%"))
    if cname:
        query = query.filter(Client.username.like("%" + cname + "%"))
    if start_time:
        query = query.filter(Loan.start_time >= start_time)
    if end_time:
        my_end_time = end_time + " 23:59:59"
        query = query.filter(Loan.start_time < my_end_time)
    if l_end == 1:
        end = (0, 2)
        query = query.filter(Loan.end.in_(end))

    if entry:
        query = query.filter(Loan.entry == entry)

    loans = query.order_by(
        Loan.create_time.desc()).order_by(Loan.id.desc()).all()

    data = [[u'序号', u'手机号码', u'客户姓名', u'贷款金额',
             u"手续费",  u"偿还金额", u"开始日期", u"结束日期", u"iphone型号",
             u"入口", u"借款状态", u"是否结束", u"还款渠道"]]

    for index, loan in enumerate(loans):
        loan_start_time = loan.start_time.strftime("%Y-%m-%d")
        loan_end_time = loan.end_time.strftime("%Y-%m-%d")

        data.append([
            index+1, loan.client.mobile, loan.client.username, loan.money,
            loan.commission, loan.repayment, loan_start_time, loan_end_time, loan.iphone,
            loan.entry_words, loan.status_words, loan.end_words,
            loan.channel_words
        ])

    return excel.make_response_from_array(data, "xlsx")
